package com.happyelements.resource
{
	import flash.display.MovieClip;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.IOErrorEvent;

	/**
	 *
	 * @author Steven
	 *
	 */
	internal class AnimationLoader
	{
		private var _url:String;
		
		private var _completeCallback:Function;
		
		private var _errorCallback:Function;
		
		private var _retry:int;
		
		public function AnimationLoader(url:String, completeCallback:Function, errorCallback:Function = null, retry:int = 2)
		{
			this._url = url;
			this._completeCallback = completeCallback;
			this._errorCallback = errorCallback;
			this._retry = retry
		}
		
		public function load():void
		{
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			
			doLoad(loader);
		}
		
		private function onLoaderComplete(event:Event):void
		{
			_completeCallback(LoaderInfo(event.currentTarget).applicationDomain);
		}
		
		private function onIOError(event:IOErrorEvent):void
		{
			if (this._retry > 0)
			{
				this._retry--;
				
				doLoad(LoaderInfo(event.currentTarget).loader);
			}
			else
			{
				this._errorCallback && _errorCallback(this._url, event);
			}
		}
		
		private function doLoad(loader:Loader):void
		{
			loader.load(new URLRequest(this._url));
		}
		
		private function dispose(loader:Loader):void
		{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaderComplete);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.close();
		}
	}
}